//
//  ProductDetailCell.m
//  sensen_ios
//
//  Created by pro on 16/2/24.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ProductDetailCell.h"

@interface ProductDetailCell () <UMSocialUIDelegate>

@property (nonatomic, strong) UILabel *introduceLabel; // 介绍视图
@property (nonatomic, strong) UILabel *presentPriceLabel; // 优惠价视图
@property (nonatomic, strong) UILabel *originalPriceLabel; // 原价视图
@property (nonatomic, strong) UILabel *salesLabel; // 销量视图



@property (nonatomic, strong) UIView *shareView; // 分享视图

@end

@implementation ProductDetailCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        [self _createViews]; // 创建视图
    }
    
    return self;
}

#pragma mark - 创建视图
- (void)_createViews {
    
    [self _createLabels]; // 创建文本视图
    [self _createShareView]; // 创建分享视图
}
// 创建 label
- (void)_createLabels {
    
    CGFloat x = 10;
    CGFloat y = 10;
    CGFloat width = SCREEN_WIDTH - 100;
    CGFloat height = 20;
    
    // 创建介绍视图
    _introduceLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _introduceLabel.font = FONT(15);
    _introduceLabel.textColor = [UIColor darkGrayColor];
    _introduceLabel.textAlignment = NSTextAlignmentLeft;
    _introduceLabel.numberOfLines = 0;
    [self.contentView addSubview:_introduceLabel];
    
    // 现价视图
    y = _introduceLabel.bottom + 15;
    width = 80;
    _presentPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _presentPriceLabel.font = FONT(18);
    _presentPriceLabel.textColor = [UIColor redColor];
    _presentPriceLabel.textAlignment = NSTextAlignmentLeft;
    [self.contentView addSubview:_presentPriceLabel];

    // 原价视图
    x = _presentPriceLabel.right + 10;
    _originalPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _originalPriceLabel.font = FONT(15);
    _originalPriceLabel.textColor = [UIColor darkGrayColor];
    _originalPriceLabel.textAlignment = NSTextAlignmentLeft;
    [self.contentView addSubview:_originalPriceLabel];
    
    // 销量视图
    y = _originalPriceLabel.top;
    width = 80;
    _salesLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _salesLabel.font = FONT(15);
    _salesLabel.textColor = [UIColor darkGrayColor];
    _salesLabel.textAlignment = NSTextAlignmentRight;
//    [self.contentView addSubview:_salesLabel];
    _salesLabel.right = SCREEN_WIDTH - 10;

}

// 创建分享视图
- (void)_createShareView {
    CGFloat x, y, width, height;
    x = _introduceLabel.right + 20;
    y = _introduceLabel.top;
    width = SCREEN_WIDTH - x - 10;
    height = width * 0.6;
    UIView *shareView = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [self addSubview:shareView];
    
    // 点击分享
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shareAction:)];
    [shareView addGestureRecognizer:tap];
    
    // 左侧的线
    x = 0;
    y = 0;
    width = 1.5;
    height = shareView.height;
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    line.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
    [shareView addSubview:line];
    
    // 图片
    width = shareView.height * 0.5;
    height = width;
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    imgView.image = [UIImage imageNamed:@"分享"];
    [shareView addSubview:imgView];
    imgView.center = CGPointMake(shareView.width / 2, imgView.center.y);
    
    // 文字
    width = shareView.width;
    height = shareView.height - imgView.height;
    y = imgView.bottom;
    x = 0;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    label.font = FONT(12);
    label.text = @"分享";
    label.textColor = [UIColor darkGrayColor];
    label.textAlignment = NSTextAlignmentCenter;
    [shareView addSubview:label];
}

#pragma mark - 点击事件
// 点击分享
//TODO: 分享相关
- (void)shareAction:(UITapGestureRecognizer *)tap {
    
    [self showShareView];
    
//    NSString *shareText = @"森森分享"; // 要分享的文字
//    NSString *url = [NSString stringWithFormat:@"%@/%@?type=product&id=%@", WEB_BASE_URL, @"User/download", _model.p_id]; // 要分享的网址
//    // 微信处理
//    [UMSocialWechatHandler setWXAppId:APPKEY_WEIXIN appSecret:APPSECRET_WEIXIN url:url];
//    [UMSocialQQHandler setQQWithAppId:APPID_QQ appKey:APPKEY_QQ url:url];
//    
//   
//    // TODO: 分享链接的问题
//    // 微博分享的处理
//    [UMSocialData defaultData].extConfig.sinaData.shareText = shareText;
//    [UMSocialData defaultData].extConfig.sinaData.urlResource.url = url;
//    [UMSocialData defaultData].extConfig.sinaData.urlResource.resourceType = UMSocialUrlResourceTypeImage;
//    
//    // 微信消息类型
//    [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
//    
//    // 微信朋友圈分享
//    [UMSocialData defaultData].extConfig.wechatTimelineData.title = @"微信朋友圈分享title";
//    [UMSocialData defaultData].extConfig.wechatTimelineData.url = url;
//    
//    // 微信好友分享
//    [UMSocialData defaultData].extConfig.wechatSessionData.title = @"微信好友分享title";
//    [UMSocialData defaultData].extConfig.wechatSessionData.url = url;
//    
//    // qq分享
//    [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
//    [UMSocialData defaultData].extConfig.qqData.title = @"QQ分享title";
//    [UMSocialData defaultData].extConfig.qzoneData.title = @"QQ空间分享title";
//    [UMSocialData defaultData].extConfig.qqData.url = url;
//    [UMSocialData defaultData].extConfig.qzoneData.url = url;
//
//    // 实现分享
//    [UMSocialSnsService presentSnsIconSheetView:self.viewController
//                                         appKey:APPKEY_UMENG_SOCIAL
//                                      shareText:shareText
//                                     shareImage:DEFAULT_IMAGE
//                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToQQ,UMShareToWechatSession,UMShareToWechatTimeline,nil]
//                                       delegate:self];
    
    
    // 使用自定义分享列表面板，则在对应的（微信，qq，微博等）分享按钮中实现下面的方法
    //    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession]
    //                                                       content:@"分享内嵌文字"
    //                                                         image:nil
    //                                                      location:nil
    //                                                   urlResource:nil
    //                                           presentedController:self
    //                                                    completion:^(UMSocialResponseEntity *response) {
    //        if (response.responseCode == UMSResponseCodeSuccess) {
    //            NSLog(@"分享成功！");
    //        }
    //    }];
}

// 分享回调代理
-(void)didFinishGetUMSocialDataInViewController:(UMSocialResponseEntity *)response
{
    //根据`responseCode`得到发送结果,如果分享成功
    if(response.responseCode == UMSResponseCodeSuccess)
    {
        //得到分享到的微博平台名
        NSLog(@"share to sns name is %@",[[response.data allKeys] objectAtIndex:0]);
    }
}


- (UIView *)shareView {
    
    if (_shareView == nil) {
        _shareView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _shareView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.6];
        _shareView.alpha = 0;
        _shareView.hidden = YES;
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        [window addSubview:_shareView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hideShareView)];
        [_shareView addGestureRecognizer:tap];
        
        UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _shareView.width, 80)];
        contentView.backgroundColor = [UIColor whiteColor];
        [_shareView addSubview:contentView];
        contentView.top = _shareView.height;
        contentView.tag = 1000;
    
        NSArray *titles = @[@"QQ", @"微信", @"朋友圈"];
        NSArray *images = @[@"QQ分享", @"微信", @"朋友圈"];
        for (int i = 0; i < titles.count; i ++) {
            CGFloat x, y = 0, width = SCREEN_WIDTH / titles.count, height = contentView.height;
            x = i * width;
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(x, y, width, height);
            button.backgroundColor = [UIColor clearColor];
            [button setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
            [button setImage:[UIImage imageNamed:images[i]] forState:UIControlStateNormal];
            [button setImageEdgeInsets:UIEdgeInsetsMake(10, (button.width / 2 - 20), 30, (button.width / 2 - 20))];
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(shareBtnAction:) forControlEvents:UIControlEventTouchUpInside];
            button.tag = 2000 + i;
            [contentView addSubview:button];
            
            x = 0;
            y = 0;
            width = button.width;
            height = 20;
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
            label.font = FONT(12);
            label.text = titles[i];
            label.textColor = [UIColor darkGrayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [button addSubview:label];
            label.bottom = button.height - 10;
        }
        
    }
    
    return _shareView;
}
- (void)showShareView {
    self.shareView.hidden = NO;
    
    UIView *contentView = [self.shareView viewWithTag:1000];
    [UIView animateWithDuration:0.3 animations:^{
        _shareView.alpha = 1;
        contentView.bottom = self.shareView.height;
    }];
}
- (void)hideShareView {
    UIView *contentView = [self.shareView viewWithTag:1000];
    [UIView animateWithDuration:0.3 animations:^{
        self.shareView.alpha = 0;
        contentView.top = self.shareView.height;
    } completion:^(BOOL finished) {
        self.shareView.hidden = YES;
    }];
}
- (void)shareBtnAction:(UIButton *)button {
    
    [self hideShareView];
    
    NSString *shareText = _model.introduction; // 要分享的文字
    NSString *url = [NSString stringWithFormat:@"%@/%@?type=product&id=%@", WEB_BASE_URL, @"User/download", _model.p_id]; // 要分享的网址
    
    // 微信处理
    [UMSocialWechatHandler setWXAppId:APPKEY_WEIXIN appSecret:APPSECRET_WEIXIN url:url];
    [UMSocialQQHandler setQQWithAppId:APPID_QQ appKey:APPKEY_QQ url:url];
    // TODO: 分享链接的问题®
    // 微博分享的处理
    [UMSocialData defaultData].extConfig.sinaData.shareText = shareText;
    [UMSocialData defaultData].extConfig.sinaData.urlResource.url = url;
    [UMSocialData defaultData].extConfig.sinaData.urlResource.resourceType = UMSocialUrlResourceTypeImage;
    
    // 微信消息类型
    [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
    
    // 微信朋友圈分享
    [UMSocialData defaultData].extConfig.wechatTimelineData.title = shareText;
    [UMSocialData defaultData].extConfig.wechatTimelineData.url = url;
    
    // 微信好友分享
    [UMSocialData defaultData].extConfig.wechatSessionData.title = shareText;
    [UMSocialData defaultData].extConfig.wechatSessionData.url = url;
    
    // qq分享
    [UMSocialData defaultData].extConfig.qqData.qqMessageType = UMSocialQQMessageTypeDefault;
    [UMSocialData defaultData].extConfig.qqData.title = shareText;
    [UMSocialData defaultData].extConfig.qzoneData.title = shareText;
    [UMSocialData defaultData].extConfig.qqData.url = url;
    [UMSocialData defaultData].extConfig.qzoneData.url = url;
    
    UIImageView * imageView  = [[UIImageView alloc] init];
    
    switch (button.tag) {
        case 2000:
        {
            [imageView setImageURLStr:self.model.main_img placeholder:DEFAULT_IMAGE];
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToQQ]
                                                               content:shareText
                                                                 image:imageView.image//[UIImage getImageFromURL:self.model.main_img]
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self.viewController
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];
        }
            break;
        case 2001:
        {
            [imageView setImageURLStr:self.model.main_img placeholder:DEFAULT_IMAGE];
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatSession]
                                                               content:shareText
                                                                 image:imageView.image
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self.viewController
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];
        }
            break;
        case 2002:
        {
            [imageView setImageURLStr:self.model.main_img placeholder:DEFAULT_IMAGE];
            [[UMSocialDataService defaultDataService] postSNSWithTypes:@[UMShareToWechatTimeline]
                                                               content:shareText
                                                                 image:imageView.image
                                                              location:nil
                                                           urlResource:nil
                                                   presentedController:self.viewController
                                                            completion:^(UMSocialResponseEntity *response) {
                                                                if (response.responseCode == UMSResponseCodeSuccess) {
                                                                    NSLog(@"分享成功！");
                                                                }
                                                            }];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 重写set
- (void)setModel:(ProductDetailModel *)model {
    if (_model != model) {
        _model = model;
        [self _setAttributes:_model];
    }
}

// 设置属性
- (void)_setAttributes:(ProductDetailModel *)model {
    
    // 商品介绍
    _introduceLabel.text = model.introduction;
    _introduceLabel.height = [model.introduction getBoundingRectOfStringSize:CGSizeMake(_introduceLabel.width, 10000) font:15].size.height + 10;
    
    // 现价，原价（区间）
    if ([model.has_sku integerValue]) { // 有多规格，则可能有最低价和最高价
        if (![model.min_price isEqualToString:model.max_price]) {
            _presentPriceLabel.text = [NSString stringWithFormat:@"￥%@~%@", model.min_price, model.max_price];
        } else {
            _presentPriceLabel.text = [NSString stringWithFormat:@"￥%@", model.min_price];
        }
        if (![model.min_ori_price isEqualToString:model.max_ori_price]) {
            _originalPriceLabel.text = [NSString stringWithFormat:@"￥%@~%@", model.min_ori_price, model.max_ori_price];
        } else {
            _originalPriceLabel.text = [NSString stringWithFormat:@"￥%@", model.min_ori_price];
        }
    } else {
        _presentPriceLabel.text = [NSString stringWithFormat:@"￥%@", model.min_price];
        _originalPriceLabel.text = [NSString stringWithFormat:@"￥%@", model.min_ori_price];
    }
    _presentPriceLabel.width = [_presentPriceLabel.text getSizeOfString:18].width;
    _presentPriceLabel.top = _introduceLabel.bottom + 10;

    _originalPriceLabel.width = [_originalPriceLabel.text getSizeOfString:15].width;
    _originalPriceLabel.left = _presentPriceLabel.right + 10;
    _originalPriceLabel.top = _presentPriceLabel.top;
    
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:_originalPriceLabel.text];
    // 删除线
    [attrString addAttribute:NSStrikethroughStyleAttributeName
                       value:@1
                       range:[_originalPriceLabel.text rangeOfString:_originalPriceLabel.text]];
    //把NSMutableAttributedString 交给 label
    _originalPriceLabel.attributedText = attrString;
    
    // 销量
//    _salesLabel.text = [NSString stringWithFormat:@"销量 %@", model.sales];
//    _salesLabel.width = [_salesLabel.text getSizeOfString:15].width;
//    _salesLabel.top = _originalPriceLabel.top;
//    _salesLabel.right = SCREEN_WIDTH - 10;

    
}


@end
